package org.itboys.shop.controller;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.itboys.baseobject.entity.Advertising;
import org.itboys.baseobject.entity.AdvertisingSC;
import org.itboys.baseobject.service.AdvertisingSCService;
import org.itboys.baseobject.service.AdvertisingService;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.tools.ImagePathUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.member.entity.Member;
import org.itboys.member.service.MemberService;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.portal.entity.PortalInfo;
import org.itboys.portal.service.PortalInfoService;
import org.itboys.product.entity.Product;
import org.itboys.product.entity.ProductCategory;
import org.itboys.product.service.ProductCategoryService;
import org.itboys.product.service.ProductService;
import org.itboys.seller.entity.Seller;
import org.itboys.seller.service.SellerService;
import org.itboys.shop.WXConstants;
import org.itboys.shop.dto.pro.WXProListDto;
import org.itboys.shop.dto.pro.WXShopListDto;
import org.itboys.shop.entity.ShopSeller;
import org.itboys.shop.service.Manager.WXProManager;
import org.itboys.shop.service.ShopSellerService;
import org.itboys.shop.tools.WeixinUserInfoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

//import weibo4j.org.json.JSONObject;

/**
 * 微信首页
 *
 * @author 
 */
@RestController
@RequestMapping("/wx/index")
public class WXIndexController extends BaseController {

    @Autowired
    private ProductService productService;
    @Autowired
    private AdvertisingService advertisingService;
    @Autowired
    private AdvertisingSCService advertisingSCService;
    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private PortalInfoService portalInfoService;
    @Autowired
    private SellerService sellerService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private WXProManager proManager;
    @Autowired
    private ShopSellerService shopSellerService;

    /**
     * 首页信息
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/info")
    public ModelAndView info(HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
//            Member member = (Member) request.getSession().getAttribute("user");
            String staticRoot = resourceHolder.getStringValue("staticRoot");
            String imagePath = staticRoot + "/upload";
            Map<String, Object> param = new HashMap<>();
//            param.put("centerId", member.getCenterId());
            param.put("centerId", 2);
            //轮播图
            param.put("type", 1);
            List<Advertising> list = advertisingService.list(param);
            int count = 0;
            for (Advertising advertising : list) {
                ++count;
                advertising.setImage(imagePath + advertising.getImage());
                advertising.setCount(count);
            }
            //大图
            param.put("type", 3);
            List<Advertising> bigList = advertisingService.list(param);
            if(bigList != null && bigList.size() > 0) {
                Advertising advertising = bigList.get(0);
                advertising.setImage(imagePath + advertising.getImage());
                model.addAttribute("bigImage", advertising);
            }
            //今日秒杀
            param.put("type", 2);
            param.put("pageNo", 1);
            param.put("pageSize", 4);
            Page<Advertising> page1 = advertisingService.page(param);
            for (Advertising advertising : page1.getData()) {
                advertising.setImage(imagePath + advertising.getImage());
                Product product = productService.getById(advertising.getDetailId());
                if(product != null) {
                    advertising.setName(product.getName());
                    advertising.setPrice(product.getProPrice()/100.0);
                    advertising.setCurrentPrice(product.getPrice()/100.0);
                }
            }
            //民宿
            param.put("type", 4);
            param.put("pageNo", 1);
            param.put("pageSize", 6);
            Page<Advertising> page2 = advertisingService.page(param);
            for (Advertising advertising : page2.getData()) {
                advertising.setImage(imagePath + advertising.getImage());
                ShopSeller seller = shopSellerService.getById(advertising.getDetailId());
                if(seller != null) {
                    advertising.setName(seller.getShopName());
                    advertising.setPrice(shopSellerService.getMinPrice(seller.getId())/100d);
                    advertising.setInfo(seller.getAdvantageDesc());
                }
            }
            //农家乐
            param.put("type", 5);
            param.put("pageNo", 1);
            param.put("pageSize", 6);
            Page<Advertising> page3 = advertisingService.page(param);
            for (Advertising advertising : page3.getData()) {
                advertising.setImage(imagePath + advertising.getImage());
                ShopSeller seller = shopSellerService.getById(advertising.getDetailId());
                if(seller != null) {
                    advertising.setName(seller.getShopName());
                    advertising.setPrice(shopSellerService.getMinPrice(seller.getId())/100d);
                    advertising.setInfo(seller.getAdvantageDesc());
                }
            }
            //门票
            param.put("type", 6);
            param.put("pageNo", 1);
            param.put("pageSize", 2);
            Page<Advertising> page4 = advertisingService.page(param);
            for (Advertising advertising : page4.getData()) {
                advertising.setImage(imagePath + advertising.getImage());
                ShopSeller seller = shopSellerService.getById(advertising.getDetailId());
                if(seller != null) {
                    advertising.setName(seller.getShopName());
                    advertising.setPrice(shopSellerService.getMinPrice(seller.getId())/100d);
                    advertising.setInfo(seller.getAdvantageDesc());
                }
            }
            //每日推荐
            param.put("type", 7);
            param.put("pageNo", 1);
            param.put("pageSize", 12);
            Page<Advertising> page5 = advertisingService.page(param);
            for (Advertising advertising : page5.getData()) {
                advertising.setImage(imagePath + advertising.getImage());
                Product product = productService.getById(advertising.getDetailId());
                if(product != null) {
                    advertising.setName(product.getName());
                    advertising.setPrice(product.getProPrice()/100.0);
                    advertising.setCurrentPrice(product.getPrice()/100.0);
                }
            }
            //游记攻略
            param.put("type", 8);
            param.put("pageNo", 1);
            param.put("pageSize", 2);
            Page<Advertising> page6 = advertisingService.page(param);
            for (Advertising advertising : page6.getData()) {
                advertising.setImage(imagePath + advertising.getImage());
                PortalInfo info = portalInfoService.getById(advertising.getDetailId());
                if(info != null) {
                    advertising.setName(info.getTitle());
                    advertising.setInfo(info.getSubtitle());
                }
            }
            //猜你喜欢
            param.put("type", 9);
            param.put("pageNo", 1);
            param.put("pageSize", 10);
            Page<Advertising> page7 = advertisingService.page(param);
            for (Advertising advertising : page7.getData()) {
                advertising.setImage(imagePath + advertising.getImage());
                Product product = productService.getById(advertising.getDetailId());
                if(product != null) {
                    advertising.setName(product.getName());
                    advertising.setPrice(product.getProPrice()/100.0);
                    advertising.setCurrentPrice(product.getPrice()/100.0);
                }
            }
            model.addAttribute("staticRoot", staticRoot);
            model.addAttribute("imageList", list);
            model.addAttribute("list1", page1.getData());
            model.addAttribute("list2", page2.getData());
            model.addAttribute("list3", page3.getData());
            model.addAttribute("list4", page4.getData());
            model.addAttribute("list5", page5.getData());
            model.addAttribute("list6", page6.getData());
            model.addAttribute("list7", page7.getData());
        } catch (Exception e) {
            logger.error("weixin index info erro!", e);
        }
        return new ModelAndView("/weixin/index");
    }

    /**
     * 商城首页
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/infoSC")
    public ModelAndView infoSC(HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            Member member = (Member) request.getSession().getAttribute("user");
            Long centerId = member.getCenterId();
            String staticRoot = resourceHolder.getStringValue("staticRoot");
            String imagePath = staticRoot + "/upload";
            Map<String, Object> param = new HashMap<>();
            param.put("centerId", centerId);
            //轮播图
            param.put("type", 1);
            List<AdvertisingSC> list = advertisingSCService.list(param);
            int count = 0;
            for (AdvertisingSC advertising : list) {
                ++count;
                advertising.setImage(imagePath + advertising.getImage());
                advertising.setCount(count);
            }
            //今日秒杀
            param.put("type", 2);
            param.put("pageNo", 1);
            param.put("pageSize", 4);
            Page<AdvertisingSC> page1 = advertisingSCService.page(param);
            for (AdvertisingSC advertising : page1.getData()) {
                advertising.setImage(imagePath + advertising.getImage());
                Product product = productService.getById(advertising.getDetailId());
                if(product != null) {
                    advertising.setName(product.getName());
                    advertising.setPrice(product.getProPrice()/100.0);
                    advertising.setCurrentPrice(product.getPrice()/100.0);
                }
            }
            //热门市场(上)
            param.put("type", 3);
            param.put("pageNo", 1);
            param.put("pageSize", 2);
            Page<AdvertisingSC> page2 = advertisingSCService.page(param);
            for (AdvertisingSC advertising : page2.getData()) {
                advertising.setImage(imagePath + advertising.getImage());
                ProductCategory category = productCategoryService.getById(advertising.getDetailId());
                if(category != null) {
                    advertising.setName(category.getName());
                    advertising.setInfo(category.getDesc());
                }
            }
            //热门市场(上)
            param.put("type", 4);
            param.put("pageNo", 1);
            param.put("pageSize", 3);
            Page<AdvertisingSC> page3 = advertisingSCService.page(param);
            for (AdvertisingSC advertising : page3.getData()) {
                advertising.setImage(imagePath + advertising.getImage());
                ProductCategory category = productCategoryService.getById(advertising.getDetailId());
                if(category != null) {
                    advertising.setName(category.getName());
                    advertising.setInfo(category.getDesc());
                }
            }
            //精品推荐
            param.put("type", 5);
            param.put("pageNo", 1);
            param.put("pageSize", 10);
            Page<AdvertisingSC> page4 = advertisingSCService.page(param);
            for (AdvertisingSC advertising : page4.getData()) {
                advertising.setImage(imagePath + advertising.getImage());
                Product product = productService.getById(advertising.getDetailId());
                if(product != null) {
                    advertising.setName(product.getName());
                    advertising.setPrice(product.getProPrice()/100.0);
                    advertising.setCurrentPrice(product.getPrice()/100.0);
                }
            }
            model.addAttribute("staticRoot", staticRoot);
            model.addAttribute("imageList", list);
            model.addAttribute("list1", page1.getData());
            model.addAttribute("list2", page2.getData());
            model.addAttribute("list3", page3.getData());
            model.addAttribute("list4", page4.getData());
        } catch (Exception e) {
            logger.error("mall index info erro!", e);
        }
        return new ModelAndView("/weixin/mall");
    }

    /**
     * 民宿首页
     * @param request
     * @param response
     * @param model  shopType 2-民宿3-基地4-景点5-农家乐
     * @return
     *//*
    @RequestMapping("/infoMS")
    public ModelAndView infoMS(@Param("pageNo")Integer pageNo,@Param("pageSize")Integer pageSize,@Param("orderBy")Integer orderBy, HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            Member member = (Member) request.getSession().getAttribute("user");
            Long centerId = member.getCenterId();
            String staticRoot = resourceHolder.getStringValue("staticRoot");
            String imagePath = staticRoot + "/upload";
            Map<String, Object> param = new HashMap<>();
            param.put("centerId", centerId);
            param.put("shopType", 2); //民宿
            List<Long> arr = new ArrayList<>();
            List<Seller> list = sellerService.list(param);
            for (Seller seller : list) {
                arr.add(seller.getId());
            }
            if(arr.size() == 0) {
                arr.add(-1L);
            }
            param.clear();
            param.put("sellerId in", arr);
            if(pageNo == null) {
                pageNo = 1;
            }
            if(pageSize == null) {
                pageSize = 10;
            }
            if(orderBy != null && orderBy != 0) {
                if(orderBy == 1){
                    param.put("orderByKey", "-soldCount");
                } else if(orderBy == 2){
                    param.put("orderByKey", "soldCount");
                } else if(orderBy == 3){
                    param.put("orderByKey", "-price");
                } else if(orderBy == 4){
                    param.put("orderByKey", "price");
                }
            }
            param.put("pageNo", pageNo);
            param.put("pageSize", pageSize);
            Page<Product> page = productService.page(param);
            List<WXProListDto> result = Lists.transform(page.getData(), product->{
                return proManager.getWXProListDto( product);
            });
//            for (Product product : page.getData()) {
//                product.setImage(imagePath + product.getImage());
//            }
            model.addAttribute("staticRoot", staticRoot);
            model.addAttribute("list", result);
            model.addAttribute("orderBy", orderBy);
            model.addAttribute("pageNo", pageNo);
            model.addAttribute("pageSize", pageSize);
        } catch (Exception e) {
            logger.error("mall index info erro!", e);
        }
        return new ModelAndView("/weixin/proList_ms");
    }

    *//**
     * 农家乐首页
     * @param request
     * @param response
     * @param model  shopType 2-民宿3-基地4-景点5-农家乐
     * @return
     *//*
    @RequestMapping("/infoNJL")
    public ModelAndView infoNJL(@Param("pageNo")Integer pageNo,@Param("pageSize")Integer pageSize,@Param("orderBy")Integer orderBy, HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            Member member = (Member) request.getSession().getAttribute("user");
            Long centerId = member.getCenterId();
            String staticRoot = resourceHolder.getStringValue("staticRoot");
            String imagePath = staticRoot + "/upload";
            Map<String, Object> param = new HashMap<>();
            param.put("centerId", centerId);
            param.put("shopType", 5); //农家乐
            List<Long> arr = new ArrayList<>();
            List<Seller> list = sellerService.list(param);
            for (Seller seller : list) {
                arr.add(seller.getId());
            }
            if(arr.size() == 0) {
                arr.add(-1L);
            }
            param.clear();
            param.put("sellerId in", arr);
            if(pageNo == null) {
                pageNo = 1;
            }
            if(pageSize == null) {
                pageSize = 10;
            }
            if(orderBy != null && orderBy != 0) {
                if(orderBy == 1){
                    param.put("orderByKey", "-soldCount");
                } else if(orderBy == 2){
                    param.put("orderByKey", "soldCount");
                } else if(orderBy == 3){
                    param.put("orderByKey", "-price");
                } else if(orderBy == 4){
                    param.put("orderByKey", "price");
                }
            }
            param.put("pageNo", pageNo);
            param.put("pageSize", pageSize);
            Page<Product> page = productService.page(param);
            List<WXProListDto> result = Lists.transform(page.getData(), product->{
                return proManager.getWXProListDto( product);
            });
//            for (Product product : page.getData()) {
//                product.setImage(imagePath + product.getImage());
//            }
            model.addAttribute("staticRoot", staticRoot);
            model.addAttribute("list", result);
            model.addAttribute("orderBy", orderBy);
            model.addAttribute("pageNo", pageNo);
            model.addAttribute("pageSize", pageSize);
        } catch (Exception e) {
            logger.error("mall index info erro!", e);
        }
        return new ModelAndView("/weixin/proList_njl");
    }

    *//**
     * 景点首页
     * @param request
     * @param response
     * @param model  shopType 2-民宿3-基地4-景点5-农家乐
     * @return
     *//*
    @RequestMapping("/infoJD")
    public ModelAndView infoJD(@Param("pageNo")Integer pageNo,@Param("pageSize")Integer pageSize,@Param("orderBy")Integer orderBy, HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            Member member = (Member) request.getSession().getAttribute("user");
            Long centerId = member.getCenterId();
            String staticRoot = resourceHolder.getStringValue("staticRoot");
            String imagePath = staticRoot + "/upload";
            Map<String, Object> param = new HashMap<>();
            param.put("centerId", centerId);
            param.put("shopType", 4); //景点
            List<Long> arr = new ArrayList<>();
            List<Seller> list = sellerService.list(param);
            for (Seller seller : list) {
                arr.add(seller.getId());
            }
            if(arr.size() == 0) {
                arr.add(-1L);
            }
            param.clear();
            param.put("sellerId in", arr);
            if(pageNo == null) {
                pageNo = 1;
            }
            if(pageSize == null) {
                pageSize = 10;
            }
            if(orderBy != null && orderBy != 0) {
                if(orderBy == 1){
                    param.put("orderByKey", "-soldCount");
                } else if(orderBy == 2){
                    param.put("orderByKey", "soldCount");
                } else if(orderBy == 3){
                    param.put("orderByKey", "-price");
                } else if(orderBy == 4){
                    param.put("orderByKey", "price");
                }
            }
            param.put("pageNo", pageNo);
            param.put("pageSize", pageSize);
            Page<Product> page = productService.page(param);
            List<WXProListDto> result = Lists.transform(page.getData(), product->{
                return proManager.getWXProListDto( product);
            });
//            for (Product product : page.getData()) {
//                product.setImage(imagePath + product.getImage());
//            }
            model.addAttribute("staticRoot", staticRoot);
            model.addAttribute("list", result);
            model.addAttribute("orderBy", orderBy);
            model.addAttribute("pageNo", pageNo);
            model.addAttribute("pageSize", pageSize);
        } catch (Exception e) {
            logger.error("mall index info erro!", e);
        }
        return new ModelAndView("/weixin/scenicList");
    }*/
}
